package org.budo.selenium.symphony;

import java.util.List;

import org.budo.selenium.BudoBrowserDriver;
import org.budo.support.lang.util.ListUtil;
import org.budo.support.lang.util.StringUtil;
import org.openqa.selenium.OutputType;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

/**
 * @author lmw
 */
@Getter
@Setter
@Slf4j
public class BudoSymphonyBrowserDriver implements BudoBrowserDriver {
    private List<BudoBrowserDriver> browserDrivers;

    @Override
    public <X> X screenshot(String url, OutputType<X> outputType) {
        if (ListUtil.isNullOrEmpty(this.getBrowserDrivers()) || StringUtil.isNullOrEmpty(url)) {
            log.warn("#24 return null, browserDrivers is null, browserDrivers=" + this.getBrowserDrivers() + ", url=" + url + ", this=" + this);
            return null;
        }

        for (BudoBrowserDriver browserDriver : this.getBrowserDrivers()) {
            X screenshot = this.screenshot(browserDriver, url, outputType);
            if (null != screenshot) {
                return screenshot;
            }
        }

        log.info("#35 return null, browserDrivers=" + this.getBrowserDrivers() + ", this=" + this);
        return null;
    }

    @Override
    public String pageSource(String url) {
        if (ListUtil.isNullOrEmpty(this.getBrowserDrivers()) || StringUtil.isNullOrEmpty(url)) {
            log.warn("#44 return null, browserDrivers is null, browserDrivers=" + this.getBrowserDrivers() + ", url=" + url + ", this=" + this);
            return null;
        }

        for (BudoBrowserDriver browserDriver : this.getBrowserDrivers()) {
            String pageSource = this.pageSource(browserDriver, url);
            if (null != pageSource && !pageSource.isEmpty()) {
                return pageSource;
            }
        }

        log.info("#55 return null, browserDrivers=" + this.getBrowserDrivers() + ", this=" + this);
        return null;
    }

    private String pageSource(BudoBrowserDriver browserDriver, String url) {
        try {
            return browserDriver.pageSource(url);
        } catch (Throwable e) {
            log.error("#63 browserDriver=" + browserDriver + ", url=" + url + ", e=" + e, e);
            return null;
        }
    }

    private <X> X screenshot(BudoBrowserDriver browserDriver, String url, OutputType<X> outputType) {
        try {
            return browserDriver.screenshot(url, outputType);
        } catch (Throwable e) {
            log.error("#45 browserDriver=" + browserDriver + ", url=" + url + ", outputType=" + outputType + ", e=" + e, e);
            return null;
        }
    }
}